package com.tcp2.frame;

import com.google.common.collect.Maps;
import com.google.common.util.concurrent.ListeningScheduledExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.common.util.concurrent.SettableFuture;
import com.tcp2.util.LoadFile;
import io.netty.channel.nio.NioEventLoopGroup;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.swing.*;
import javax.swing.border.TitledBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import java.awt.*;
import java.awt.event.*;
import java.util.Vector;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.Executors;

/**
 * Author: <张锦煌>
 * Time: 2015-09-15 14:41
 * Copyright (C) 2015 Xiamen Yaxon Networks CO.,LTD.
 */

/*
出租车版本操作界面
 */
public class TaxiFrame extends JFrame{
    private LoadFile loadFile=new LoadFile();
    private ListeningScheduledExecutorService timerService;
    private Vector vector0=new Vector();
    private   JTable table=new JTable();
    private static ConcurrentMap<Long,Integer> taskIdMap= Maps.newConcurrentMap();


    public TaxiFrame(JPanel jp) throws Exception {
        //服务器连接
        JPanel jp0 = new JPanel();
        JPanel jp1 = new JPanel();
        JPanel jp5 = new JPanel();
        TitledBorder connBorder = new TitledBorder("服务器连接");
        TitledBorder sctBorder = new TitledBorder("选择操作");
        jp1.setBorder(connBorder);
        jp5.setBorder(sctBorder);
        jp0.add(jp1);
        jp0.add(jp5);
        JLabel address = new JLabel("IP地址");
        JLabel port = new JLabel("TCP端口号");
        final ServerConfig serverConfig = loadFile.loadServerConfig("./conf/app.properties");
        final JTextField addressT = new JTextField(serverConfig.getAddress(), 15);
        final JTextField portT = new JTextField(serverConfig.getPort(), 10);
        jp1.add(address);
        jp1.add(addressT);
        jp1.add(port);
        jp1.add(portT);

        //选择操作
        JButton sct1 = new JButton("全选");
        JButton sct2 = new JButton("取消");
        JButton sct3 = new JButton("在线");
        JButton sct6 = new JButton("运行");
        JButton sct4 = new JButton("离线");
        JButton sct5 = new JButton("任务中");
        jp5.add(sct1);
        jp5.add(sct2);
        jp5.add(sct3);
        jp5.add(sct4);
        jp5.add(sct5);
        jp5.add(sct6);

        //选择操作事件
        sct1.addActionListener(new ActionListener() {   //全选
            @Override
            public void actionPerformed(ActionEvent e) {
                table.selectAll();
            }
        });
        sct2.addActionListener(new ActionListener() {   //取消选择
            @Override
            public void actionPerformed(ActionEvent e) {
                table.clearSelection();
            }
        });
        sct3.addActionListener(new ActionListener() {    //选择上线车辆
            @Override
            public void actionPerformed(ActionEvent e) {
                table.clearSelection();
                for (int i = 0; i < table.getRowCount(); i++) {
                    String s = (String) table.getValueAt(i, 2);
                    if (s.equals("在线")) {
                        table.addRowSelectionInterval(i, i);
                    }
                }
            }
        });
        sct4.addActionListener(new ActionListener() {     //选择下线车辆
            @Override
            public void actionPerformed(ActionEvent e) {
                table.clearSelection();
                for (int i = 0; i < table.getRowCount(); i++) {
                    String s = (String) table.getValueAt(i, 2);
                    if (s.equals("离线")) {
                        table.addRowSelectionInterval(i, i);
                    }
                }
            }
        });
        sct5.addActionListener(new ActionListener() {     //选择下线车辆
            @Override
            public void actionPerformed(ActionEvent e) {
                table.clearSelection();
                for (int i = 0; i < table.getRowCount(); i++) {
                    String s = (String) table.getValueAt(i, 2);
                    if (s.equals("任务中")) {
                        table.addRowSelectionInterval(i, i);
                    }
                }
            }
        });
        sct6.addActionListener(new ActionListener() {   //选择运行中车辆
            @Override
            public void actionPerformed(ActionEvent e) {
                table.clearSelection();
                for (int i = 0; i < table.getRowCount(); i++) {
                    String s = (String) table.getValueAt(i, 2);
                    if (s.equals("运行")) {
                        table.addRowSelectionInterval(i, i);
                    }
                }
            }
        });

        //创建表格数据
        JPanel jp2 = new JPanel();
        TitledBorder msgBorder = new TitledBorder("车台信息");
        jp2.setBorder(msgBorder);
        DefaultTableModel t0 = null;
        try {
         //   vector0 = loadFile.readerCsv("./conf/taxiInfoExp.csv");  //不支持选择数据来源，车辆信息手动从数据库导出或文件添加
        } catch (Exception e) {
            e.printStackTrace();
        }
        Vector n = new Vector();
        n.addElement("ISU标识");
        n.addElement("车牌号");
        n.addElement("状态");
        n.addElement("选中");
        t0 = new DefaultTableModel(vector0, n) {  //重写方法设置表格双击不可编辑
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        table.setModel(t0);
        table.getColumnModel().getColumn(3).setCellRenderer(new TableCellRenderer() {
            @Override
            public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
                JCheckBox ck = new JCheckBox();
                ck.setSelected(isSelected);
                ck.setHorizontalAlignment((int) 0.5f);
                return ck;
            }
        });

        //实现Ctrl+点击鼠标左键事件（点击多选表格行）
        table.addMouseListener(new MouseAdapter() {
            Robot robot = null;

            @Override
            public void mouseEntered(MouseEvent e) { //鼠标进入表格
                try {
                    robot = new Robot();
                } catch (AWTException e1) {
                    e1.printStackTrace();
                }
                robot.keyPress(KeyEvent.VK_CONTROL);//按下ctrl键
            }

            @Override
            public void mouseExited(MouseEvent e) {  //鼠标离开表格
                try {
                    robot = new Robot();
                } catch (AWTException e1) {
                    e1.printStackTrace();
                }
                robot.keyRelease(KeyEvent.VK_CONTROL); //释放ctrl键
            }
        });
        table.setPreferredScrollableViewportSize(new Dimension(650, 280));
        JScrollPane s = new JScrollPane(table);
        jp2.add(s);

        //终端操作
        JPanel jp3 = new JPanel();
        TitledBorder optBorder = new TitledBorder("终端操作");
        jp3.setBorder(optBorder);
        JButton btn1 = new JButton("车台连接");
        JButton btn2 = new JButton("业务抢答");
        btn2.setEnabled(false);
        JButton btn3 = new JButton("业务完成");
        JButton btn4 = new JButton("更多操作");
        JPanel gpsJ = new JPanel();
        TitledBorder gpsBorder = new TitledBorder("定时发送GPS");
        gpsJ.setBorder(gpsBorder);
        JLabel timeRate = new JLabel("间隔");
        final JTextField rateT = new JTextField("5", 5);
        JLabel dw = new JLabel("秒");
        JButton btn51 = new JButton("发送");
        JButton btn52 = new JButton("停止");
        Box g1 = Box.createHorizontalBox();
        g1.add(Box.createHorizontalStrut(10));
        g1.add(timeRate);
        g1.add(rateT);
        g1.add(dw);
        g1.add(Box.createHorizontalStrut(20));
        Box g2 = Box.createHorizontalBox();
        g2.add(btn51);
        g2.add(btn52);
        Box vg = Box.createVerticalBox();
        vg.add(g1);
        vg.add(Box.createVerticalStrut(10));
        vg.add(g2);
        gpsJ.add(vg);
        Box b1 = Box.createHorizontalBox();
        b1.add(btn1);
        Box b2 = Box.createHorizontalBox();
        b2.add(btn2);
        Box b3 = Box.createHorizontalBox();
        b3.add(btn3);
        Box b4 = Box.createHorizontalBox();
        b4.add(btn4);
        Box b5 = Box.createHorizontalBox();
        b5.add(gpsJ);
        Box vb = Box.createVerticalBox();
        vb.add(Box.createVerticalStrut(30));
        vb.add(b1);
        vb.add(Box.createVerticalStrut(30));
        vb.add(b2);
        vb.add(Box.createVerticalStrut(30));
        vb.add(b3);
        vb.add(Box.createVerticalStrut(30));
        vb.add(b4);
        vb.add(Box.createVerticalStrut(30));
        vb.add(b5);
        vb.add(Box.createVerticalStrut(10));
        jp3.add(vb);

        btn1.addActionListener(new ActionListener() {     //终端连接
            @Override
            public void actionPerformed(ActionEvent e) {
                boolean flag = false;
                if (table.getSelectedRowCount() <= 0) {
                    JOptionPane.showMessageDialog(null, "请至少选择一辆车台！");
                } else {
                    for (int rowindex : table.getSelectedRows()) {
                        String state = (String) table.getValueAt(rowindex, 2);
                        if ((state.equals("在线"))) {
                            JOptionPane.showMessageDialog(null, "存在已在线车辆！");
                            flag = false;
                            break;
                        } else {
                            flag = true;
                        }
                    }
                    if (flag) {
                        timerService = MoreExecutors.listeningDecorator(Executors.newScheduledThreadPool(8));

                        NioEventLoopGroup ioThreadPool = new NioEventLoopGroup();

                        for (final int rowindex : table.getSelectedRows()) {
                            final long sim = Long.parseLong((String) table.getValueAt(rowindex, 0));
                            final SettableFuture<Integer> future = SettableFuture.create();
                        }
                    }
                }
            }
        });
    }
    }

                     /*       final Connection c = new Connection( ioThreadPool);
                            ListenableFuture<Object> listenableFuture = timerService.submit(new Callable<Object>() {
                                @Override
                                public Object call() throws Exception {
                                    c.setAddress(addressT.getText());
                                    c.setPort(portT.getText());
                                    c.connTaxi(sim,future);
                                    return null;
                                }
                            });
                            Futures.addCallback(listenableFuture, new FutureCallback<Object>() {
                                @Override
                                public void onSuccess(Object o) {
                                    int state = 0;
                                    try {
                                        state = future.get();
                                    } catch (Exception e1) {
                                        e1.printStackTrace();
                                    }
                                    if (state == TaxiChannelHA.ST_LOGIN_ON) {
                                        table.setValueAt("在线", rowindex, 2);
                                    }
                                    if (state == TaxiChannelHA.ST_LOGIN_OUT) {
                                        JOptionPane.showMessageDialog(null, "登录失败！");
                                    }
                                }
                                @Override
                                public void onFailure(Throwable throwable) {
                                    return;
                                }
                            });
                        }
                    }
                }
            }
        });*/

                         /*   btn2.addActionListener(new ActionListener() {
                                @Override
                                public void actionPerformed(ActionEvent e) {
                                    if (table.getSelectedRowCount() != 1) {
                                        JOptionPane.showMessageDialog(null, "请选择一辆车台！");
                                    } else {
                                        String state = (String) table.getValueAt(table.getSelectedRow(), 2);
                                        if (!(state.equals("在线"))) {
                                            JOptionPane.showMessageDialog(null, "车辆不在线！");
                                        } else {
                                            timerService = MoreExecutors.listeningDecorator(Executors.newScheduledThreadPool(2));
                                            final SettableFuture<Integer> future = SettableFuture.create();
                                            final long sim = Long.parseLong((String) table.getValueAt(table.getSelectedRow(), 0));
                                            final Bean0B01 b0B01 = new Bean0B01();
                                            b0B01.setId(MyQuene.removeTask(sim));
                                            b0B01.sim = sim;
                                            b0B01.msgId = 0x0B01;
                                            ListenableFuture<Object> listenableFuture = timerService.submit(new Callable<Object>() {
                                                @Override
                                                public Object call() throws Exception {
                                                    new TaxiChannelHA(sim, future).do_0B01(b0B01);
                                                    return null;
                                                }
                                            });
                                            Futures.addCallback(listenableFuture, new FutureCallback<Object>() {
                                                @Override
                                                public void onSuccess(Object o) {
                                                    int state = 0;
                                                    try {
                                                        state = future.get();
                                                        taskIdMap.putIfAbsent(sim, b0B01.getId());
                                                    } catch (Exception e1) {
                                                        e1.printStackTrace();
                                                    }
                                                    if (state == TaxiChannelHA.ST_TASKING) {
                                                        table.setValueAt("任务中", table.getSelectedRow(), 2);
                                                    }
                                                    if (state == TaxiChannelHA.ST_LOGIN_ON) {
                                                        JOptionPane.showMessageDialog(null, "抢答失败！");
                                                    }
                                                }

                                                @Override
                                                public void onFailure(Throwable throwable) {
                                                    return;
                                                }
                                            });

                                        }
                                    }
                                }
                            });*/

     /*   btn3.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (table.getSelectedRowCount() != 1) {
                    JOptionPane.showMessageDialog(null, "请选择一辆车台！");
                } else {
                    String state = (String) table.getValueAt(table.getSelectedRow(), 2);
                    if (!(state.equals("任务中"))) {
                        JOptionPane.showMessageDialog(null, "车辆不在任务中！");
                    } else {
                        timerService = MoreExecutors.listeningDecorator(Executors.newScheduledThreadPool(2));
                        final SettableFuture<Integer> future = SettableFuture.create();
                        final long sim = Long.parseLong((String) table.getValueAt(table.getSelectedRow(), 0));
                        final Bean0B07 b0B07=new Bean0B07();
                        b0B07.setId(taskIdMap.remove(sim));
                        b0B07.sim=sim;
                        b0B07.msgId=0x0B07;
                        ListenableFuture<Object> listenableFuture = timerService.submit(new Callable<Object>() {
                            @Override
                            public Object call() throws Exception {
                                new TaxiChannelHA(sim,future).do_0B07(b0B07);
                                return null;
                            }
                        });
                        Futures.addCallback(listenableFuture, new FutureCallback<Object>() {
                            @Override
                            public void onSuccess(Object o) {
                                int state = 0;
                                try {
                                    state = future.get();
                                } catch (Exception e1) {
                                    e1.printStackTrace();
                                }
                                if (state == TaxiChannelHA.ST_LOGIN_ON) {
                                    table.setValueAt("在线", table.getSelectedRow(), 2);
                                }
                                if (state == TaxiChannelHA.ST_TASKING) {
                                    JOptionPane.showMessageDialog(null, "提交失败！");
                                }
                            }
                            @Override
                            public void onFailure(Throwable throwable) {
                                return;
                            }
                        });

                    }
                }
            }
        });*/

                            //更多终端操作
    /*    btn4.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                boolean flag = false;
                if (table.getSelectedRowCount() <= 0) {
                    JOptionPane.showMessageDialog(null, "请至少选择一辆车台！");
                } else {
                    for (int rowindex : table.getSelectedRows()) {
                        String state = (String) table.getValueAt(rowindex, 2);
                        if ((state.equals("离线"))) {
                            JOptionPane.showMessageDialog(null, "请选择在线车台！");
                            flag = false;
                            break;
                        } else {
                            flag = true;
                        }
                    }
                    if (flag) {
                        MoreAction905 ma = new MoreAction905();
                        ma.moreAction905(table);
                    }
                }
            }
        });*/

                            //定时发送GPS数据
       /* btn51.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                boolean flag = false;
                if (table.getSelectedRowCount() <= 0) {
                    JOptionPane.showMessageDialog(null, "请至少选择一辆车台！");
                } else {
                    for (int rowindex : table.getSelectedRows()) {
                        String state = (String) table.getValueAt(rowindex, 2);
                        if (!(state.equals("在线"))) {
                            JOptionPane.showMessageDialog(null, "请选择在线车台！");
                            flag = false;
                            break;
                        } else {
                            flag = true;
                        }
                    }
                    if (flag) {
                        for (int rowindex : table.getSelectedRows()) {
                            TaxiChannelHA tch=new TaxiChannelHA(true);
                            long sim = Long.parseLong((String) table.getValueAt(rowindex, 0));
                            int rate= Integer.parseInt(rateT.getText());
                            tch.GPSTimer(sim,rate*1000);
                            table.setValueAt("运行", rowindex, 2);
                        }
                    }
                }
            }
        });
        btn52.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                for (int rowindex : table.getSelectedRows()) {
                    new TaxiChannelHA(false);
                    table.setValueAt("在线", rowindex, 2);
                }
            }
        });

        TaskThread taskThread=new TaskThread(btn2);
        taskThread.start();

        Box jpb1=Box.createHorizontalBox();
        Box jpb2=Box.createHorizontalBox();
        jpb1.add(jp0);
        jpb2.add(jp2);jpb2.add(jp3);
        Box jph=Box.createVerticalBox();
        jph.add(jpb1);jph.add(jpb2);
        jp.add(jph,"taxi");

    }*/

                            //接收中心电召任务线程
  /*  class TaskThread extends Thread{
        private Logger logger = LoggerFactory.getLogger(TaskThread.class);
        private  JButton jb;
        private boolean flag=false;
        public  TaskThread(JButton jb){
            this.jb=jb;
        }
        @Override
        public void run() {
            while (true) {

                    if(!((MyQuene.taskMap).isEmpty())){
                        jb.setEnabled(true);
                        if(flag&& MainFrame.versionState==true) {
                            JOptionPane.showMessageDialog(null, "接收到中心任务订单，可抢答！");
                            flag=false;
                        }
                    }else{
                        jb.setEnabled(false);
                        flag=true;
                    }
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }*/


